package com.founder.service.impl;

import com.founder.core.constant.PayConstant;
import com.founder.core.dao.PayOrderRespository;
import com.founder.core.domain.MchNotify;
import com.founder.core.domain.PayOrder;
import com.founder.core.log.MyLog;
import com.founder.service.IMchNotifyService;
import com.founder.service.IPayChannel4AliService;
import com.founder.service.IPayChannel4WxService;
import com.founder.service.IPayOrderService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.Optional;

@Transactional
@Service
public class PayOrderServiceImpl implements IPayOrderService {

    private final MyLog _log = MyLog.getLog(PayOrderServiceImpl.class);

    @Autowired
    IMchNotifyService mchNotifyService;

    @Autowired
    PayOrderRespository payOrderRespository;

    @Autowired
    IPayChannel4WxService payChannel4WxService;

    @Autowired
    IPayChannel4AliService payChannel4AliService;

    @Override
    public PayOrder selectPayOrder(String payOrderId) {
        _log.info("查询支付订单：{}", payOrderId);
        Optional<PayOrder> optional = payOrderRespository.findById(payOrderId);
        PayOrder payOrder = null;
        if (optional.isPresent()){
            payOrder = optional.get();
        }
        return payOrder;
    }

    @Override
    public PayOrder selectPayOrder(String mchId, String mchOrderNo, String payOrderId) {
        _log.info("根据商户号：{}，商户订单号：{}，支付单号：{}查询订单", mchId, mchOrderNo, payOrderId);
        PayOrder payOrder = new PayOrder();
        payOrder.setMchId(mchId);
        if (StringUtils.isNotBlank(mchOrderNo)) {
            payOrder.setMchOrderNo(mchOrderNo);
        }
        if (StringUtils.isNotBlank(payOrderId)) {
            payOrder.setPayOrderId(payOrderId);
        }
        Example<PayOrder> example = Example.of(payOrder);
        Optional<PayOrder> opt = payOrderRespository.findOne(example);
        return opt.isPresent() ? opt.get() : null;
    }

    @Override
    public PayOrder selectPayOrder(String mchId, String mchOrderNo, String payOrderId, String executeNotify, String executeQuery) {
        PayOrder payOrder = this.selectPayOrder(mchId, mchOrderNo, payOrderId);

        if (payOrder != null) {
            boolean isQuery = Boolean.parseBoolean(executeQuery);
            _log.info("是否订单支付状态查询同步.{}", isQuery);
            if (isQuery) {
                String channelId = payOrder.getChannelId();
                if (PayConstant.PAY_CHANNEL_ALIPAY_BR.equals(channelId) || PayConstant.PAY_CHANNEL_ALIPAY_QR.equals(channelId)){
                    String result = payChannel4AliService.doAliQueryReq(channelId, payOrder);
                    _log.info("查询支付宝订单返回：{}", result);
                } else if (PayConstant.PAY_CHANNEL_WX_NATIVE.equals(channelId) || PayConstant.PAY_CHANNEL_WX_MICROPAY.equals(channelId)){
                    String result = payChannel4WxService.doWxQueryReq(channelId, payOrder);
                    _log.info("查询微信订单返回：{}", result);
                }
            }

            boolean isNotify = Boolean.parseBoolean(executeNotify);
            _log.info("是否订单再次发送业务支付通知.{}", isNotify);
            if (isNotify) {

            }
        }

        return payOrder;
    }

    @Override
    public int createPayOrder(PayOrder payOrder) {
        String payOrderId = payOrder.getPayOrderId();
        if (payOrderRespository.existsById(payOrderId)){
            _log.error("订单{}已经存在",payOrderId);
            return 0;
        }
        payOrder.setNotifyCount(0);
        payOrder.setCreateTime(new Date());
        payOrder.setUpdateTime(new Date());
        payOrderRespository.save(payOrder);
        return 1;
    }

    @Override
    public int updateStatus4Ing(String payOrderId) {
        PayOrder payOrder = this.selectPayOrder(payOrderId);
        if (payOrder == null){
            _log.error("订单{}不存在",payOrderId);
            return 0;
        }
        if (payOrder.getStatus() != PayConstant.PAY_STATUS_INIT){
            _log.error("订单{}状态不允许更新,可能已支付",payOrderId);
            return 0;
        }
        payOrder.setStatus(PayConstant.PAY_STATUS_PAYING);
        payOrder.setPaySuccTime(System.currentTimeMillis());
        payOrderRespository.save(payOrder);
        return 1;
    }

    @Override
    public int updateStatus4Success(String payOrderId) {
        PayOrder payOrder = this.selectPayOrder(payOrderId);
        if (payOrder == null){
            _log.error("订单{}不存在",payOrderId);
            return 0;
        }
        if (payOrder.getStatus() != PayConstant.PAY_STATUS_PAYING){
            _log.error("订单{}状态不允许更新,可能已支付",payOrderId);
            return 0;
        }
        payOrder.setStatus(PayConstant.PAY_STATUS_SUCCESS);
        payOrder.setPaySuccTime(System.currentTimeMillis());
        payOrderRespository.save(payOrder);
        return 1;
    }

    @Override
    public int updateStatus4Complete(String payOrderId) {
        PayOrder payOrder = this.selectPayOrder(payOrderId);
        if (payOrder == null){
            _log.error("订单{}不存在",payOrderId);
            return 0;
        }
        if (payOrder.getStatus() < PayConstant.PAY_STATUS_INIT){
            _log.error("订单{}状态不允许更新,可能未支付",payOrderId);
            return 0;
        }
        payOrder.setStatus(PayConstant.PAY_STATUS_COMPLETE);
        payOrder.setPaySuccTime(System.currentTimeMillis());
        payOrderRespository.save(payOrder);
        return 1;
    }

    @Override
    public int updateStatus4Closed(String payOrderId) {
        PayOrder payOrder = this.selectPayOrder(payOrderId);
        if (payOrder == null){
            _log.error("订单{}不存在",payOrderId);
            return 0;
        }
        if (payOrder.getStatus() >= PayConstant.PAY_STATUS_SUCCESS){
            _log.error("订单{}状态不允许更新,可能已支付",payOrderId);
            return 0;
        }
        _log.info("针对支付宝设置过期");
        payOrder.setStatus(PayConstant.PAY_STATUS_EXPIRED);//TRADE_CLOSED（未付款交易超时关闭，或支付完成后全额退款）
        payOrderRespository.save(payOrder);
        return 1;
    }

    @Override
    public int updateStatus4Failed(String payOrderId) {
        PayOrder payOrder = this.selectPayOrder(payOrderId);
        if (payOrder == null){
            _log.error("订单{}不存在",payOrderId);
            return 0;
        }
        if (payOrder.getStatus() >= PayConstant.PAY_STATUS_SUCCESS){
            _log.error("订单{}状态不允许更新,可能已支付",payOrderId);
            return 0;
        }
        _log.info("针对微信设置过期");
        payOrder.setStatus(PayConstant.PAY_STATUS_EXPIRED);//PAYERROR--支付失败(其他原因，如银行返回失败)
        payOrderRespository.save(payOrder);
        return 1;
    }

    @Override
    public int updateNotify4Count(String payOrderId, Integer cnt) {
        PayOrder payOrder = this.selectPayOrder(payOrderId);
        if (payOrder == null){
            _log.error("订单{}不存在",payOrderId);
            return 0;
        }

        _log.info("更新订单通知次数");
        payOrder.setNotifyCount(cnt);
        payOrder.setLastNotifyTime(System.currentTimeMillis());
        payOrderRespository.save(payOrder);

        _log.info("创建或更新商户通知");
        MchNotify mchNotify = mchNotifyService.selectMchNotify(payOrderId);
        if (mchNotify == null){
            mchNotify = new MchNotify();
            mchNotify.setOrderId(payOrderId);
            mchNotify.setMchId(payOrder.getMchId());
            mchNotify.setMchOrderNo(payOrder.getMchOrderNo());
            mchNotify.setOrderType("1");//'订单类型:1-支付,2-转账,3-退款'
            mchNotify.setNotifyUrl(payOrder.getNotifyUrl());
            mchNotify.setResult("通知中");//通知响应结果
            mchNotify.setStatus(1);//通知状态,1-通知中,2-通知成功,3-通知失败
            mchNotify.setCreateTime(new Date());
        }
        mchNotify.setStatus(2);
        mchNotify.setNotifyCount(cnt);
        mchNotify.setLastNotifyTime(new Date());
        int result = mchNotifyService.saveMchNotify(mchNotify);

        return result;
    }

    @Override
    public int updateChannelOrderNo(String payOrderId, String channelOrderNo) {
        PayOrder payOrder = this.selectPayOrder(payOrderId);
        if (payOrder == null){
            _log.error("订单{}不存在",payOrderId);
            return 0;
        }
        if (StringUtils.isBlank(channelOrderNo)){
            _log.error("微信支付宝订单号{}不允许为空。", channelOrderNo);
            return 0;
        }
        payOrder.setChannelOrderNo(channelOrderNo);
        payOrderRespository.save(payOrder);
        return 1;
    }
}
